package com.las.bot.cmd.jisu;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.las.bot.common.Constant;
import com.utils.image.ImageCreateWrapper;
import com.utils.image.ImgCreateOptions;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseCommand;
import com.las.cmd.judge.ImgCmd;
import com.las.utils.HttpUtils;
import com.las.utils.JsonUtils;
import com.las.utils.StrUtils;
import com.las.utils.mirai.CmdUtil;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.springframework.context.annotation.Scope;

@BotCmd(funName = "新闻")
@Scope("prototype")
public class NewsCmd extends BaseCommand {

    private final Logger logger = Logger.getLogger(ImgCmd.class);

    private final String[] mores = {"头条", "新闻", "国内", "国际", "政治", "财经", "体育", "娱乐", "军事", "教育", "科技", "NBA", "股票", "星座", "女性", "育儿"};


    public NewsCmd() {
        super("新闻", "头条", "国内", "国际", "政治", "财经", "体育", "娱乐", "军事", "教育", "科技", "NBA",
                "股票", "星座", "女性", "育儿");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String cmd, ArrayList<String> args) throws Exception {
        String channel = cmd.substring(0, 2);
        logger.info("新闻频道：" + channel);
        if (args.size() < 1) {
            int size = 30;
            String api = "https://api.jisuapi.com/news/get?channel=" + channel + "&start=0&num=" + size + "&appkey=09ba2644e1e957c8";
            String result = HttpUtils.doGet(api);
            JSONObject obj = JsonUtils.getJsonObjectByJsonString(result);
            Integer status = obj.getInteger("status");
            if (0 != status) {
                CmdUtil.sendMessage("新闻的API欠费了，请改天再试~", userId, id, type);
                return;
            }
            JSONArray jsonArray = obj.getJSONObject("result").getJSONArray("list");
            String[] content = new String[size + 1];
            content[0] = channel + "频道前" + size + "条信息如下：";
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject newsObj = jsonArray.getJSONObject(i);
                String title = newsObj.getString("title");
                String time = newsObj.getString("time");
                String url = newsObj.getString("weburl");
                logger.info(title + " -- " + time + "\n" + url);
                String info = channel + (i + 1) + "、" + title;
                content[i + 1] = info;
            }
            String uuid = genImg(content);
            String fileName = uuid + ".png";
            logger.info("生成新闻图片：" + fileName);
            // 实现准备好空集合
            ArrayList<String> urls = new ArrayList<>();
            File file = new File(fileName);
            try {
                String objectName = uuid + Constant.BUCKET_PNG;
                // 下一步将目标图上传到阿里云
                String endpoint = Constant.HTTPS + Constant.OSS;
                String accessKeyId = Constant.BUCKET_ID;
                String accessKeySecret = Constant.BUCKET_KEY;
                String bucketName = Constant.BUCKET_NAME;
                // 上传到阿里云OSS
                OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                ossClient.putObject(bucketName, objectName, file);
                ossClient.shutdown();
                String imgUrl = Constant.HTTPS + Constant.BUCKET_NAME + "." + Constant.OSS + objectName;
                logger.info("上传到阿里云原图：" + imgUrl);
                urls.add(imgUrl);
                if (CollectionUtil.isNotEmpty(urls)) {
                    CmdUtil.sendImgMessage(urls, userId, id, type);
                }
            } catch (Exception e) {
                logger.error("生成新闻图失败：" + e.getMessage());
                CmdUtil.sendMessage("生成新闻图失败...请稍后再试...", userId, id, type);
            } finally {
                // 上传成功后需要删除本地图
                if (file.exists()) {
                    file.delete();
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.append("输入指令：#频道 数字 即可查看，例如：#").append(channel).append(" ").append(6).append("\n");
            sb.append("更多频道还有：").append(Arrays.toString(mores));
            if (StrUtils.isNotBlank(sb.toString())) {
                CmdUtil.sendMessage(sb.toString(), userId, id, type);
            }
        } else {
            String number = args.get(0).trim();
            if (!StrUtils.isNumeric(number)) {
                CmdUtil.sendMessage("参数不对，请检查", userId, id, type);
                return;
            }
            int num = Integer.parseInt(number);
            if (num <= 0) {
                CmdUtil.sendMessage("参数不对，请检查", userId, id, type);
                return;
            }
            if (num > 500) {
                CmdUtil.sendMessage("参数太大，顶多就500多条", userId, id, type);
                return;
            }
            String api = "https://api.jisuapi.com/news/get?channel=" + channel + "&start=" + (num - 1) + "&num=1&appkey=09ba2644e1e957c8";
            String result = HttpUtils.doGet(api);
            JSONObject obj = JsonUtils.getJsonObjectByJsonString(result);
            Integer status = obj.getInteger("status");
            if (0 != status) {
                CmdUtil.sendMessage("新闻的API欠费了，请改天再试~", userId, id, type);
                return;
            }
            JSONArray jsonArray = obj.getJSONObject("result").getJSONArray("list");
            if (CollectionUtil.isEmpty(jsonArray)) {
                CmdUtil.sendMessage("暂无数据，请改天再试~", userId, id, type);
                return;
            }
            JSONObject newsObj = jsonArray.getJSONObject(0);
            String title = newsObj.getString("title");
            String url = newsObj.getString("weburl");
            String msg = title + "\n" + url;
            CmdUtil.sendMessage(msg, userId, id, type);
            //后续弄一个新闻模板
            String tempStr = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID=\"146\" templateID=\"1\" action=\"web\" brief=\"[分享] NEWS_TEMP_TITLE\" sourceMsgId=\"0\" url=\"NEWS_TEMP_URL?from=wap\" flag=\"0\" adverSign=\"0\" multiMsgFlag=\"0\"><item layout=\"2\" advertiser_id=\"0\" aid=\"0\"><picture cover=\"https://qq.ugcimg.cn/v1/0p8ol82v8m1tam3dii6au378vrj4f4po2o1n96tjkpi6kh07qri4u2k1k507g4gmpa3sij7bemt14ap72ivh1bmgsv7srl049ri9d4ke9ck8ee9m2qdacgrf3kb8q557cl3psbhh4lesrmv1d0i3s2er3btp1gc59p05d45n1kka52p4hqrg/7cd9tgtcu359jgbf3ne6f0ei3o\" w=\"0\" h=\"0\" /><title>NEWS_TEMP_TITLE</title><summary>NEWS_TEMP_TITLE</summary></item><source name=\"QQ浏览器\" icon=\"https://url.cn/PWkhNu\" url=\"https://url.cn/UQoBHn\" action=\"app\" a_actionData=\"com.tencent.mtt://NEWS_TEMP_URL?from=wap\" i_actionData=\"tencent100446242://NEWS_TEMP_URL?from=wap\" appid=\"-1\" /></msg>";
            tempStr = tempStr.replaceAll("NEWS_TEMP_TITLE", title);
            tempStr = tempStr.replaceAll("NEWS_TEMP_URL", url);
            logger.info("新闻模板：" + tempStr);
        }

    }

    private static String genImg(String[] content) throws IOException {
        int w = 400;
        int leftPadding = 10;
        int topPadding = 40;
        int bottomPadding = 40;
        int linePadding = 10;
        Font font = new Font("宋体", Font.BOLD, 18);
        // String[] names = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
        // Font font = new Font(names[new Random().nextInt(names.length)], Font.BOLD, 18);
        ImageCreateWrapper.Builder build = ImageCreateWrapper.build()
                .setImgW(w)
                .setLeftPadding(leftPadding)
                .setTopPadding(topPadding)
                .setBottomPadding(bottomPadding)
                .setLinePadding(linePadding)
                .setFont(font)
                .setAlignStyle(ImgCreateOptions.AlignStyle.LEFT)
                .setFontColor(new Color(185, 23, 65));


        for (String line : content) {
            build.setFontSize(18);
            build.drawContent(line);
        }

        BufferedImage img = build.asImage();
        String id = StrUtils.uuid();
        ImageIO.write(img, "png", new File(id + ".png"));
        return id;

    }
}
